<?php

class Center_QuestionController extends CenterController
{

    /**
     * 咨询列表
     */
    public function listQuestions()
    {

        $params = Input::all();

        $rules = array(
            'type' => array(
                'regex:/^(question|pay_text|pay_phone|pay_company)$/i'
            ),
            'status' => array(
                'regex:/^(new|replied|wait_for_evaluation|complete|cancelled)$/i'
            )
        );
        $messages = array(
            'type.regex' => '请提交正确的类别',
            'status.regex' => '请提交正确的状态',
        );

        $validator = Validator::make($params, $rules, $messages);
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView('errors.400', $validator->errors(), 400);
        }

        $type = isset($params['type']) ? $params['type'] : null;
        $post_status = isset($params['status']) ? $params['status'] : null;
        $page = Input::get('page', 1);
        $rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
        $offset = ($page - 1) * $rows_per_page;

        if ($this->user->status == User::STATUS_VERIFIED_LAWYER) {
            $questions = $this->getQuestionsForLawyer($type, $post_status, $rows_per_page, $offset);
        } else {
            //$questions = $this->getQuestionsForNormalUser($type, $post_status, $rows_per_page, $offset);
            $questions = $this->getQuestionsForNormalUser($type, $post_status , $rows_per_page, $offset);
        }

        if ($questions) {
            $questionArr = $questions->toArray();
            foreach ($questionArr as &$question) {
                $question['status_name'] = UtilsHelper::getPostStatusStr($question['status']);
                $question['type_name'] = UtilsHelper::getTypeStr($question['type']);
                $question['post_category'] = UtilsHelper::getWorkScopeName($question['post_category']);
                $question['transitions'] = $this->getAvailableTransitions($question['status'], $question['id'], $question['type']);
                $question['creator_avatar'] = UtilsHelper::getImage($question['creator_avatar'], "img/dfimg.png");
                $question['difference_date'] = UtilsHelper::differenceFormat($question['created_at']);
                if(isset($question['comments'])){
                    foreach($question['comments'] as $comment) {
                        $comment->difference_date = UtilsHelper::differenceFormat($question['created_at']);
                    }
                }
                // prepare the assigned lawyer information
                $this->getAssignedLawyerInfo($question['id'], $question);

                // 显示联系律师和联系用户的电话号码
                if ($question['status'] == Post::STATUS_REPLIED
                    && $question['type'] == Post::TYPE_PAY_PHONE
                    && $this->user->status == User::STATUS_VERIFIED_LAWYER) {
                        $creator = User::find($question['creator_id']);
                        $question['creator_phone'] = $creator->phone;
                    }
            }
        } else {
            $questionArr = [];
        }
        return $this->makeView('center.question.list', $questionArr);
    }

    protected function getQuestionsForNormalUser($type, $post_status , $rows_per_page, $offset)
    {
        $questions = Post::leftJoin('user', 'posts.creator_id', '=', 'user.id')
            ->leftJoin('post_order', 'post_order.post_id', '=', 'posts.id' )
            ->leftJoin('order', 'order.id', '=', 'post_order.order_id' )
            ->select('order.id', 'order.order_no', 'order.price', 'posts.id', 'posts.title', 'posts.content', 'posts.type', 'posts.status', 'posts.post_category', 'posts.created_at', 'posts.updated_at', 'posts.creator_id', 'user.realname as creator_realname', 'user.avatar as creator_avatar')
            ->where('posts.creator_id', $this->user->id);
        if(!empty($type)){
            $questions = $questions->where('posts.type', $type);
        }else{
            $questions = $questions->whereIn('posts.type', [
                Post::TYPE_PAY_PHONE,
                Post::TYPE_PAY_COMPANY,
                Post::TYPE_PAY_TEXT,
            ]);
        }
        if(!empty($post_status)){
            $questions = $questions->where('posts.status', $post_status);
        }else{
            $questions = $questions->whereIn('posts.status', [
                Post::STATUS_NEW,
                Post::STATUS_REPLIED,
                Post::STATUS_REFUSED,
                Post::STATUS_WAIT_FOR_EVALUATION,
                Post::STATUS_COMPLETE
            ]);
        }
        $questions = $questions->where('posts.customer_visible', Post::CUSTOMER_VISIBLE)
            ->orderBy('order.created_at', 'DESC')
            ->groupBy('posts.id')
            ->take($rows_per_page)
            ->skip($offset)
            ->get();
        return $questions;
    }

	protected function getQuestionsForLawyer($type, $post_status, $rows_per_page, $offset)
	{
		$questions = Post::leftJoin('post_thread', 'posts.id', '=', 'post_thread.post_id')
            ->leftJoin('user', 'posts.creator_id', '=', 'user.id')
            ->leftJoin('post_order', 'post_order.post_id', '=', 'posts.id' )
            ->leftJoin('order', 'order.id', '=', 'post_order.order_id' )
            ->select('order.price', 'order.order_no', 'posts.id', 'posts.title', 'posts.content', 'posts.type', 'posts.status', 'posts.post_category', 'posts.created_at', 'posts.updated_at', 'posts.creator_id', 'user.realname as creator_realname', 'user.avatar as creator_avatar');

		if (!empty($type)) {
			$questions = $questions->where('posts.type', $type);
		} else {
			$questions = $questions->whereIn('posts.type', [
				Post::TYPE_PAY_PHONE,
				Post::TYPE_PAY_COMPANY,
				Post::TYPE_PAY_TEXT,
			]);
		}
		if (!empty($post_status)) {
			$questions = $questions->where('posts.status', $post_status);
		} else {
			$questions = $questions->whereIn('posts.status', [
				Post::STATUS_NEW,
				Post::STATUS_REPLIED,
				Post::STATUS_REFUSED,
				Post::STATUS_WAIT_FOR_EVALUATION,
				Post::STATUS_COMPLETE,
			]);
		}
		$questions = $questions->where('posts.lawyer_visible', Post::LAWYER_VISIBLE)->where('post_thread.user_id', $this->user->id)->orderBy('order.created_at', 'DESC')->groupBy('posts.id')->take($rows_per_page)->skip($offset)->get();

		return $questions;
	}

    /**
     * 根据不同类型的用户来得到后续的动作
     *
     * @param $status 状态码
     */
    protected function getAvailableTransitions($status, $id, $postType)
    {
        if ($this->user->status == User::STATUS_VERIFIED_LAWYER) {
            return $this->getTransitionsForLawyer($status, $id, $postType);
        } else {
            return $this->getTransitionsForNormalUser($status, $id, $postType);
        }
    }

    protected function getTransitionsForLawyer($status, $id, $postType)
    {
        $transitions = [];
        switch ($status) {
            case Post::STATUS_NEW:
                if (in_array($postType, [
                    Post::TYPE_QUESTION,
                    Post::TYPE_PAY_COMPANY
                ])) {
                    $transitions[] = array(
                        'to_take' => route('center.question.to_take', array(
                            'id' => $id
                        ))
                    );
                } else
                    if (in_array($postType, [
                        Post::TYPE_PAY_TEXT,
                        Post::TYPE_PAY_PHONE
                    ])) {
                        $transitions[] = array(
                            'to_accept' => route('center.question.to_accept', array(
                                'id' => $id
                            ))
                        );
                        $transitions[] = array(
                            'to_refuse' => route('center.question.to_refuse', array(
                                'id' => $id
                            ))
                        );
                    }
                break;
            case Post::STATUS_REPLIED:
                $transitions[] = array(
                    'to_ask' => route('center.question.to_ask', array(
                        'id' => $id
                    ))
                );
                break;
            case Post::STATUS_WAIT_FOR_EVALUATION:
                break;
//            case Post::STATUS_COMPLETE:
//                $transitions[] = array(
//                    'to_remove' => route('center.question.to_remove', array(
//                        'id' => $id
//                    ))
//                );
//                break;
//            case Post::STATUS_CANCELLED:
//                $transitions[] = array(
//                    'to_remove' => route('center.question.to_remove', array(
//                        'id' => $id
//                    ))
//                );
//                break;
        }
        return $transitions;
    }

    protected function getTransitionsForNormalUser($status, $id, $postType)
    {
        $transitions = [];
        switch ($status) {
//            case Post::STATUS_NEW:
//                $transitions[] = array(
//                    'to_cancel' => route('center.question.to_cancel', array(
//                        'id' => $id
//                    ))
//                );
//                break;
            case Post::STATUS_REPLIED:
                $transitions[] = array(
                    'to_ask' => route('center.question.to_ask', array(
                        'id' => $id
                    ))
                );
                $transitions[] = array(
                    'to_complete' => route('center.question.to_confirm', array(
                        'id' => $id
                    ))
                );
                break;
            case Post::STATUS_WAIT_FOR_EVALUATION:
                $transitions[] = array(
                    'to_evaluate' => route('center.question.to_evaluate', array(
                        'id' => $id
                    ))
                );
                if ($postType == Post::TYPE_QUESTION) {
                    $transitions[] = array(
                        'to_tip_with_wallet' => route('wallet.reward')
                    );
                }
                break;
            case Post::STATUS_COMPLETE:
                if (in_array($postType, [
                    Post::TYPE_QUESTION,
                    Post::TYPE_PAY_TEXT
                ])) {
                    $transitions[] = array(
                        'details' => route('question.view', array(
                            'id' => $id
                        ))
                    );
                }
//                $transitions[] = array(
//                    'to_remove' => route('center.question.to_remove', array(
//                        'id' => $id
//                    ))
//                );
                break;
//            case Post::STATUS_CANCELLED:
//                $transitions[] = array(
//                    'to_remove' => route('center.question.to_remove', array(
//                        'id' => $id
//                    ))
//                );
//                break;
        }
        return $transitions;
    }

    public function viewItem($id)
    {
        $post = $this->getQuestion($id);

        if (! is_a($post, 'Post')) {
            return $post;
        }

        switch ($post->type) {
            case Post::TYPE_QUESTION:
                return $this->viewQuestion($post);
                break;
            case Post::TYPE_PAY_TEXT:
            case Post::TYPE_PAY_PHONE:
                return $this->viewOrder($post->id);
                break;
            case Post::TYPE_PAY_COMPANY:
                return $this->viewCompanyOrder($post->id);
                break;
        }
    }

    protected function viewQuestion($post)
    {
        $post->load('attachments');
        $post = $post->toArray();
        $postArr = [];
        $postArr['id'] = $post['id'];
        $postArr['status'] = $post['status'];
        $postArr['type'] = $post['type'];
        $postArr['type_name'] = UtilsHelper::getTypeStr($post['type']);
        $postArr['title'] = $post['title'];
        $postArr['content'] = $post['content'];
        $postArr['post_category'] = UtilsHelper::getWorkScopeName($post['post_category']);
        $postArr['updated_at'] = $post['updated_at'];
        $postArr['created_at'] = $post['created_at'];
        //$postArr['difference_date'] = UtilsHelper::differenceFormat($post['created_at']);
        $postArr['creator_id'] = $post['creator_id'];
        $postArr['attachments'] = $post['attachments'];
        $postArr['transitions'] = $this->getAvailableTransitions($postArr['status'], $postArr['id'], $post['type']);
        foreach ($postArr['attachments'] as $key => &$attachment) {
            $attachment['url'] = UtilsHelper::getImage($attachment['src']);
            if (!$attachment['url']) {
                unset($postArr['attachments'][$key]);
            }
        }
        // prepare the assigned lawyer information
        $this->getAssignedLawyerInfo($postArr['id'], $postArr);

        // prepare the creator's information
        $this->getCreatorInfo($postArr);

        Post::readPost($post['id']);
        return $this->makeView('center.question.view.question', $postArr);
    }

    protected function viewOrder($id)
    {
        $order = Post::leftJoin('post_order', 'post_order.post_id', '=', 'posts.id')
            ->leftJoin('order', 'post_order.order_id', '=', 'order.id')
            ->select('order.price','posts.id', 'posts.type', 'posts.title', 'posts.content', 'posts.status', 'posts.post_category', 'posts.created_at', 'posts.updated_at', 'posts.creator_id', 'order.order_no')
            ->where('posts.id', $id)
            ->first();
        $order->load('attachments');
        $orderArr = $order->toArray();
        $orderArr['type_name'] = UtilsHelper::getTypeStr($orderArr['type']);
        $orderArr['difference_date'] = UtilsHelper::differenceFormat($orderArr['created_at']);
        $orderArr['status_name'] = UtilsHelper::getPostStatusStr($orderArr['status']);
        $orderArr['post_category'] = UtilsHelper::getWorkScopeName($orderArr['post_category']);
        $orderArr['transitions'] = $this->getAvailableTransitions($orderArr['status'], $orderArr['id'], $orderArr['type']);
        foreach ($orderArr['attachments'] as $key => &$attachment) {
            $attachment['url'] = UtilsHelper::getImage($attachment['src']);
            if (!$attachment['url']) {
                unset($orderArr['attachments'][$key]);
            }
        }

        // prepare the assigned lawyer information
        $this->getAssignedLawyerInfo($id, $orderArr);

        // prepare the creator's information
        $this->getCreatorInfo($orderArr);

        // 显示联系律师和联系用户的电话号码
        if ($orderArr['status'] == Post::STATUS_REPLIED
            && $orderArr['type'] == Post::TYPE_PAY_PHONE
            && $this->user->status == User::STATUS_VERIFIED_LAWYER) {
            $creator = User::find($orderArr['creator_id']);
            $orderArr['creator_phone'] = $creator->phone;
        }

        Post::readPost($id);
        return $this->makeView('center.question.view.order', $orderArr);
    }

    protected function viewCompanyOrder($id)
    {
        $order = Post::leftJoin('post_order', 'post_order.post_id', '=', 'posts.id')->leftJoin('order', 'post_order.order_id', '=', 'order.id')
            ->leftJoin('company_server', 'company_server.order_id', '=', 'order.id')
            ->select('posts.id', 'posts.type', 'posts.status', 'posts.title', 'posts.created_at', 'posts.updated_at', 'posts.creator_id', 'company_server.email', 'company_server.company_name', 'company_server.province', 'company_server.city', 'company_server.district', 'company_server.memo', 'company_server.invoice', 'order.order_no')
            ->where('posts.id', $id)
            ->first();
        $orderArr = $order->toArray();
        $orderArr['province'] = AreaHelper::areaCodeToName($orderArr['province']);
        $orderArr['city'] = AreaHelper::areaCodeToName($orderArr['city']);
        $orderArr['district'] = AreaHelper::areaCodeToName($orderArr['district']);
        $orderArr['type_name'] = UtilsHelper::getTypeStr($orderArr['type']);
        $orderArr['transitions'] = $this->getAvailableTransitions($orderArr['status'], $orderArr['id'], $orderArr['type']);
        $orderArr['difference_date'] = UtilsHelper::differenceFormat($orderArr['created_at']);

        // prepare the assigned lawyer information
        $this->getAssignedLawyerInfo($id, $orderArr);

        // prepare the creator's information
        $this->getCreatorInfo($orderArr);

        Post::readPost($id);
        return $this->makeView('center.question.view.company_order', $orderArr);
    }

    protected function getAssignedLawyerInfo($id, &$info)
    {
        $post = Post::find($id);
        $assignedLawyer = $post->getAssignedLawyer();
        if ($assignedLawyer) {
            $info['lawyer_name'] = $assignedLawyer->realname;
            $info['lawyer_phone'] = $assignedLawyer->phone;
            $info['lawyer_id'] = $assignedLawyer->id;
            $info['lawyer_avatar'] = UtilsHelper::getImage($assignedLawyer->avatar, 'img/df.png');
        }
    }

    protected function getCreatorInfo(&$info)
    {
        $creator = User::find($info['creator_id']);
        $info['creator_name'] = $creator->realname;
        $info['creator_phone'] = $creator->phone;
    }

    /**
     * 获取问题，如果出错了，会返回合适的Response
     *
     * @param integer $id
     */
    protected function getQuestion($id)
    {
        try {
            $post = Post::findOrFail($id);
        } catch (ModelNotFoundException $e) {
            return $this->makeView('errors.404', '没有找到符合要求的纪录。', 404);
        } catch (Exception $ex) {
            Log::error($ex);
            return $this->makeView('errors.503', '咨询律师失败，请稍后再试。', 503);
        }
        return $post;
    }
}
